﻿using Nop.Core.Infrastructure;
using Nop.Services.Logging;
using Nop.Services.Tasks;
using System;

namespace Nop.Services.WindAlert
{
    /// <summary>
    /// Represents a task for sending queued message 
    /// </summary>
    public partial class UpdateStationsTask : ITask
    {

        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            var spotService = EngineContext.Current.Resolve<ISpotService>();
            var windDataService = EngineContext.Current.Resolve<IWindDataService>();

            var spotStations = spotService.GetAllSpots(isStation: true);
            foreach (var spotStation in spotStations)
            {
                try
                {
                    var stationData = windDataService.UpdateStation(spotStation);
                    var lastStation = windDataService.GetWindDataBySpotIdTop1(spotStation.Id);
                    if(lastStation == null)
                        windDataService.InsertWindData(stationData);
                    else if (lastStation.StationTime != stationData.StationTime)
                        windDataService.InsertWindData(stationData);

                }
                catch (Exception exc)
                {
                    var logger = EngineContext.Current.Resolve<ILogger>();
                    logger.Error(string.Format("Error updateing stations. {0}", exc.Message), exc);
                    continue;
                }
            }
        }
    }
}
